package fr.vvins.core.test;

import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;

import javax.sql.DataSource;

import org.dbunit.DataSourceBasedDBTestCase;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.util.fileloader.FlatXmlDataFileLoader;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;

public class EntityTestCase extends DataSourceBasedDBTestCase {

	@Autowired
	private DataSource dataSource;
	
	@Override
	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource aDatasource) {
		dataSource = aDatasource;
	}

	 @Override
	protected void setUpDatabaseConfig(DatabaseConfig config) {
	     config.setProperty(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, true);
	 }
	
	@Before
	public void load() throws Exception {
		super.setUp();
	}
	
	@After
	public void clear(){
		try {
			synchronized (this) {
				IDatabaseConnection c = getConnection();
			    Statement s = c.getConnection().createStatement();
			    s.execute("SET DATABASE REFERENTIAL INTEGRITY FALSE");
			    Set<String> tables = new HashSet<String>();
			    ResultSet rs = s.executeQuery("select TABLE_SCHEM, TABLE_NAME " +
			        "from INFORMATION_SCHEMA.system_tables " +
			        "where table_type='TABLE'");
			    while (rs.next()) {
			        if (!rs.getString(2).startsWith("DUAL_")) {
			            tables.add(rs.getString(1) + "." + rs.getString(2));
			        }
			    }
			    rs.close();
			    for (String table : tables) {
			        s.executeUpdate("DELETE FROM " + table);
			    }
			    s.execute("SET DATABASE REFERENTIAL INTEGRITY TRUE");	
			    s.close();
				c.close();
			}
       } catch (Exception e) {
    	   Assert.fail(e.getMessage());
       } 
	}
	
	protected IDataSet getDataSet() throws Exception {
		synchronized (this) {
			return new FlatXmlDataFileLoader().load("/" + (this.getClass().getName()).replace(".", "/") +".xml");
		}
	}

}
